package com.farm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.farm.entity.CartItem;
import com.farm.entity.Order;
import com.farm.entity.OrderItem;
import com.farm.entity.OrderStatus;
import com.farm.entity.Product;
import com.farm.entity.User;
import com.farm.repository.OrderRepository;
import com.farm.repository.ProductRepository;
import com.farm.repository.UserRepository;

@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private CartService cartService;

    @Autowired
    private UserRepository userRepository;

    @Transactional
    public List<Order> createOrdersFromCart(User user, String contactName, String contactPhone, String deliveryAddress) {
        List<CartItem> cartItems = cartService.getCartItems(user);
        if (cartItems.isEmpty()) {
            throw new RuntimeException("购物车是空的");
        }

        // 按农户分组购物车商品
        Map<User, List<CartItem>> itemsByFarmer = cartItems.stream()
                .collect(Collectors.groupingBy(item -> item.getProduct().getFarmer()));

        // 计算总金额
        BigDecimal totalAmount = cartItems.stream()
                .map(item -> item.getProduct().getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 检查余额是否足够
        if (user.getBalance().compareTo(totalAmount) < 0) {
            throw new RuntimeException("余额不足，请先充值");
        }

        List<Order> orders = new ArrayList<>();

        // 为每个农户创建订单
        for (Map.Entry<User, List<CartItem>> entry : itemsByFarmer.entrySet()) {
            User farmer = entry.getKey();
            List<CartItem> farmerItems = entry.getValue();

            Order order = new Order();
            order.setUser(user);
            order.setStatus(OrderStatus.PENDING);
            order.setContactName(contactName);
            order.setContactPhone(contactPhone);
            order.setDeliveryAddress(deliveryAddress);

            List<OrderItem> orderItems = new ArrayList<>();
            BigDecimal orderTotal = BigDecimal.ZERO;

            for (CartItem cartItem : farmerItems) {
                Product product = cartItem.getProduct();
                
                // 检查库存
                if (product.getStock() < cartItem.getQuantity()) {
                    throw new RuntimeException(product.getName() + " 库存不足");
                }

                // 创建订单项
                OrderItem orderItem = new OrderItem();
                orderItem.setOrder(order);
                orderItem.setProduct(product);
                orderItem.setQuantity(cartItem.getQuantity());
                orderItem.setPrice(product.getPrice());
                orderItems.add(orderItem);

                // 更新库存
                product.setStock(product.getStock() - cartItem.getQuantity());
                productRepository.save(product);

                // 计算订单金额
                orderTotal = orderTotal.add(product.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())));
            }

            order.setItems(orderItems);
            order.setTotalAmount(orderTotal);
            orders.add(orderRepository.save(order));

            // 更新农户余额
            farmer.setBalance(farmer.getBalance().add(orderTotal));
            userRepository.save(farmer);
        }

        // 扣除买家余额
        user.setBalance(user.getBalance().subtract(totalAmount));
        userRepository.save(user);

        // 清空购物车
        cartService.clearCart(user);

        return orders;
    }

    @Transactional
    public Order updateOrderStatus(Long orderId, OrderStatus status) {
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
        order.setStatus(status);
        return orderRepository.save(order);
    }

    public List<Order> findByUser(User user) {
        return orderRepository.findByUser(user);
    }

    public List<Order> findByStatus(OrderStatus status) {
        return orderRepository.findByStatus(status);
    }

    public Order findById(Long id) {
        return orderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Order not found"));
    }

    public List<Order> findOrdersByFarmer(User farmer) {
        return orderRepository.findByFarmer(farmer);
    }

    public List<Order> findAllOrders() {
        return orderRepository.findAll();
    }

    public List<Order> searchOrders(String keyword, OrderStatus status) {
        if (keyword != null && !keyword.trim().isEmpty()) {
            if (status != null) {
                return orderRepository.findByUserNameContainingAndStatus(keyword, status);
            }
            return orderRepository.findByUserNameContaining(keyword);
        }
        
        if (status != null) {
            return orderRepository.findByStatus(status);
        }
        
        return orderRepository.findAll();
    }

    public void updateOrder(Order order) {
        orderRepository.save(order);
    }
} 